/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

// 等待设备就绪
document.addEventListener('deviceready', function() {
    console.log('设备就绪，快递查询功能可用');
    // 页面加载时获取快递公司列表
    loadExpressCompanies();
}, false);

// 快递公司列表
let expressCompanies = [];

// 状态映射
const statusMap = {
    'TRANSPORT': { text: '运输中', class: 'transport' },
    'SIGNED': { text: '已签收', class: 'signed' },
    'COLLECT': { text: '已揽收', class: 'collect' }
};

// 加载快递公司列表
function loadExpressCompanies() {
    const token = localStorage.getItem('express_api_token');
    if (!token) {
        console.log('未找到Token，跳过加载快递公司列表');
        return;
    }

    const params = new URLSearchParams();
    params.append('token', token);

    fetch('https://v3.alapi.cn/api/kd/com', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: params.toString()
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络请求失败: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('快递公司列表响应:', data);
        
        if (data.success && data.code === 200 && Array.isArray(data.data)) {
            expressCompanies = data.data;
            updateCompanySelect(data.data);
        } else {
            console.error('获取快递公司列表失败:', data.message);
        }
    })
    .catch(error => {
        console.error('获取快递公司列表错误:', error);
    });
}

// 更新快递公司下拉框
function updateCompanySelect(companies) {
    const select = document.getElementById('com');
    // 保留"自动识别"选项
    const autoOption = select.querySelector('option[value=""]');
    select.innerHTML = '';
    if (autoOption) {
        select.appendChild(autoOption);
    }
    
    companies.forEach(company => {
        const option = document.createElement('option');
        option.value = company.code;
        option.textContent = company.name;
        select.appendChild(option);
    });
}

// 表单提交处理
document.getElementById('express-form').addEventListener('submit', function(e) {
    e.preventDefault();
    queryExpress();
});

// 查询快递
function queryExpress() {
    const submitBtn = document.getElementById('submit-btn');
    const loading = document.getElementById('loading');
    const errorMessage = document.getElementById('error-message');
    const resultContainer = document.getElementById('result-container');
    
    // 获取表单数据
    const formData = {
        token: document.getElementById('token').value.trim(),
        number: document.getElementById('number').value.trim(),
        com: document.getElementById('com').value,
        phone: document.getElementById('phone').value.trim()
    };
    
    // 验证快递单号
    if (!formData.number) {
        showError('请输入快递单号');
        return;
    }
    
    // 验证token
    if (!formData.token) {
        showError('请输入API Token');
        return;
    }
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitBtn.textContent = '查询中...';
    loading.classList.add('show');
    errorMessage.classList.remove('show');
    resultContainer.classList.remove('show');
    
    // 构建请求参数
    const params = new URLSearchParams();
    params.append('token', formData.token);
    params.append('number', formData.number);
    if (formData.com) {
        params.append('com', formData.com);
    }
    if (formData.phone) {
        params.append('phone', formData.phone);
    }
    
    // 发送POST请求
    fetch('https://v3.alapi.cn/api/kd', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: params.toString()
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络请求失败: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('API响应:', data);
        
        if (data.success && data.code === 200) {
            displayExpressInfo(data.data);
            // 如果成功查询，更新快递公司列表
            if (!expressCompanies.length) {
                loadExpressCompanies();
            }
        } else {
            showError(data.message || '查询失败，请检查参数');
        }
    })
    .catch(error => {
        console.error('请求错误:', error);
        showError('请求失败: ' + error.message + '。请检查网络连接或API Token是否正确');
    })
    .finally(() => {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.textContent = '查询';
        loading.classList.remove('show');
    });
}

// 显示错误信息
function showError(message) {
    const errorMessage = document.getElementById('error-message');
    errorMessage.textContent = message;
    errorMessage.classList.add('show');
}

// 显示快递信息
function displayExpressInfo(data) {
    const resultContainer = document.getElementById('result-container');
    const expressInfo = document.getElementById('express-info');
    
    let html = '';
    
    // 快递基本信息
    html += '<div class="info-header">';
    html += '<div class="info-header-left">';
    html += `<h3>${data.com_text || '未知快递公司'}</h3>`;
    html += `<p>快递单号：${data.nu || '未知'}</p>`;
    html += '</div>';
    
    // 状态标签
    const status = statusMap[data.status] || { text: data.status_desc || '未知', class: 'transport' };
    html += `<span class="status-badge ${status.class}">${status.text}</span>`;
    html += '</div>';
    
    // 物流轨迹列表
    if (data.info && Array.isArray(data.info) && data.info.length > 0) {
        html += '<ul class="tracking-list">';
        data.info.forEach((item, index) => {
            const itemStatus = statusMap[item.status] || { text: item.status_desc || '', class: 'transport' };
            html += '<li class="tracking-item">';
            html += '<div class="tracking-content">';
            html += `<div class="tracking-time">${item.time || ''}</div>`;
            html += `<div class="tracking-text">${item.content || ''}</div>`;
            if (item.status_desc) {
                html += `<div style="margin-top: 5px; font-size: 12px; color: #7f8c8d;">状态：${item.status_desc}</div>`;
            }
            html += '</div>';
            html += '</li>';
        });
        html += '</ul>';
    } else {
        html += '<div style="text-align: center; padding: 20px; color: #7f8c8d;">暂无物流轨迹信息</div>';
    }
    
    expressInfo.innerHTML = html;
    
    // 显示结果容器
    resultContainer.classList.add('show');
    
    // 滚动到结果区域
    resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 尝试从本地存储加载token
    const savedToken = localStorage.getItem('express_api_token');
    if (savedToken) {
        document.getElementById('token').value = savedToken;
        // 如果有token，加载快递公司列表
        loadExpressCompanies();
    }
    
    // 保存token到本地存储
    document.getElementById('token').addEventListener('blur', function() {
        const token = this.value.trim();
        if (token) {
            localStorage.setItem('express_api_token', token);
            // Token更新后重新加载快递公司列表
            loadExpressCompanies();
        }
    });
    
    console.log('快递查询页面加载完成');
});

